<template>
  <div class="login-container">
    <!-- 登录卡片 -->
    <div class="login-card">
      <div class="login-header">
        <h2 class="login-title">吉林油田公司科学技术奖网评系统</h2>
        <p class="login-subtitle">请登录您的账号</p>
      </div>

      <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
      >
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              prefix-icon="el-icon-user"
              :disabled="loading"
          ></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="el-icon-lock"
              :disabled="loading"
              show-password
          ></el-input>
        </el-form-item>

        <el-form-item class="remember-me">
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <el-link type="primary" :underline="false" class="forgot-password">忘记密码？</el-link>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              style="width: 100%;"
              @click="handleLogin"
              :loading="loading"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 页脚信息 -->
    <div class="login-footer">
      <p>© 2025 吉林油田公司科学技术奖网评系统 版权所有</p>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/user'
import { setToken } from '@/utils/auth' // 假设存在存储token的工具函数
import {jwtDecode} from "jwt-decode";

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ]
      },
      rememberMe: false,
      loading: false
    }
  },

  created() {
    // 如果之前记住了账号，从本地存储中读取
    this.loadRememberedUser()
  },

  methods: {
    // 加载记住的用户信息
    loadRememberedUser() {
      const rememberedUser = localStorage.getItem('rememberedUser')
      if (rememberedUser) {
        try {
          const user = JSON.parse(rememberedUser)
          this.loginForm.username = user.username
          this.rememberMe = true
        } catch (e) {
          console.error('解析记住的用户信息失败', e)
        }
      }
    },

    // 处理登录逻辑
    handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (!valid) {
          return
        }

        this.loading = true
        try {
          // 调用登录接口
          const response = await login(this.loginForm)
          // 假设接口返回格式: { code: 200, data: 'token字符串', msg: '登录成功' }
          if (response.code === '200' && response.data) {
            // 解析token 获取权限信息 如果不是系统管理员或公司管理员禁止登录
            const decodedToken = jwtDecode(response.data);
            let role = decodedToken['role'];
            if (role !== 'ROLE_SYSADMIN' && role !== 'ROLE_ADMIN_L1') {
              this.$message.error('登录失败，您没有权限登录网评系统')
              return;
            }

            // 存储token
            setToken(response.data)

            // 如果需要记住用户，存储用户名
            if (this.rememberMe) {
              localStorage.setItem('rememberedUser', JSON.stringify({
                username: this.loginForm.username
              }))
            } else {
              localStorage.removeItem('rememberedUser')
            }

            this.$message.success('登录成功，正在跳转...')

            // 登录成功后跳转到首页
            setTimeout(() => {
              this.$router.push('/')
            }, 1000)
          } else {
            this.$message.error(response.msg || '登录失败，请检查用户名和密码')
          }
        } catch (error) {
          console.error('登录请求失败', error)
          this.$message.error('登录失败，请稍后重试')
        } finally {
          this.loading = false
        }
      })
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.login-card {
  width: 400px;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-title {
  font-size: 24px;
  color: #1f2d3d;
  margin-bottom: 10px;
}

.login-subtitle {
  font-size: 14px;
  color: #8392a5;
}

.login-form {
  margin-top: 20px;
}

.remember-me {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.forgot-password {
  font-size: 14px;
}

.login-footer {
  margin-top: 20px;
  color: #8392a5;
  font-size: 12px;
}
</style>
